﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Handrise.CDCable.Mobile.Business
{
    /// <summary>
    /// 升级服务
    /// </summary>
    public class UpdateService
    {
        private Synchronize synchronize = new Synchronize();

        private long fileLen;

        private string serverVersion = "";

        public event UpdateProcessHandler OnUpdateProcess;

        /// <summary>
        /// 开始升级
        /// </summary>
        public void StartUpdate()
        {
            //获取需要下载的次数
            int downloadCount = (int)(fileLen -1) / (1024 * 100) + 1;
            byte[] buffer;

            //创建临时文件
            FileStream fs = new FileStream(AppLogic.GetLocalPath() + "\\Update\\update.udd",FileMode.Create);

            try
            {
                try
                {
                    for (int i = 0; i < downloadCount; i++)
                    {
                        if (synchronize.DownloadUpdateFile(i, out buffer))
                        {
                            fs.Seek(0, SeekOrigin.End);
                            fs.Write(buffer, 0, buffer.Length);
                            ShowInfo("新系统下载中...", (i + 1) * 100 / downloadCount);
                        }
                        else
                        {
                            ShowInfo("下载失败", 100);
                            return;
                        }
                    }
                }
                catch (Exception e)
                {
                    ShowInfo("下载失败", 100);
                    return;
                }
            }
            finally
            {
                fs.Close();
            }

        }

        /// <summary>
        /// 查询是否需要升级
        /// </summary>
        /// <returns></returns>
        public bool QueryNeedUpdate()
        {
            return synchronize.GetNeedUpdate(out fileLen, out serverVersion);
        }

        private void ShowInfo(string info, int percent)
        {
            if (OnUpdateProcess != null)
                OnUpdateProcess(info, percent);
        }

        public long ZipFileLen
        {
            get { return fileLen; }
        }

        public string ServerVersion
        {
            get { return serverVersion; }
        }

    }

    public delegate void UpdateProcessHandler(string info, int percent);
}
